package com.leyou.sh.user.web;

import com.leyou.sh.auth.dto.UserDetail;
import com.leyou.sh.auth.interceptors.LoginInterceptor;
import com.leyou.sh.auth.utils.UserContext;
import com.leyou.sh.user.dto.UserDTO;
import com.leyou.sh.user.entity.User;
import com.leyou.sh.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

/**
 * @author balisong_fcs
 * @date 2021/1/9 11:04
 * @desc
 */
@RestController
@RequestMapping("/info")
public class UserController {
    @Autowired
    private UserService userService;

    /**
     * 校验手机号或用户名是否存在
     * @param data 用户名或手机号
     * @param type 数据类型：1是用户名；2是手机；其它是参数有误
     * @return true：可以使用; false：不可使用
     */
    @GetMapping("/exists/{data}/{type}")
    public ResponseEntity<Boolean> exists(@PathVariable("data") String data, @PathVariable("type") Integer type) {
        return ResponseEntity.ok(userService.exists(data, type));
    }

    /**
     * 用户填写注册信息;后台接收电话号码进行验证,发送消息
     * @param phone
     * @return
     */
    @PostMapping("/code")
    public ResponseEntity<Void> sendCode(
            @RequestParam("phone") String phone)
    {
        this.userService.sendCode(phone);
        return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
    }

    /**
     * 新用户填写user信息以及验证码;进行用户注册
     * @param user 接收前端表单user数据
     * @param code 接收前端表单验证码信息
     * @return 无返回
     */
    @PostMapping
    public ResponseEntity<Void> registerUser(
            @Valid User user,
            @RequestParam("code") String code
    ){
        this.userService.registerUser( user, code);
        return ResponseEntity.status(HttpStatus.CREATED).build();
    }

    /**
     * 根绝用户名和密码,查询用户信息
     * @param username
     * @param password
     * @return
     */
    @GetMapping
    public ResponseEntity<UserDTO> queryUserByNameAndPassWord(
            @RequestParam("username")String username,
            @RequestParam("password")String password

    ){
        return ResponseEntity.ok(this.userService.queryUserByNameAndPassWord(username,password));
    }

    /**
     * 校验cookie,返回用户信息
     * @param
     * @return
     */
    @GetMapping("/me")
    public ResponseEntity<UserDetail> getUser(){
        return ResponseEntity.ok(UserContext.getUser());
    }

}
